package cn.com.franke.util;

import net.sf.json.JsonConfig;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;

import java.io.IOException;
import java.util.Date;

public class JSONUtil {
	
	private static ObjectMapper objectMapper = new ObjectMapper();
	static {
		Feature f = Feature.valueOf("WRITE_NULL_PROPERTIES");
		objectMapper.configure(f, false);
		
	}
	
	
	/**
	 * 解析date类型
	* @Title: getDateJsonConfig 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @return  
	* @return JsonConfig    返回类型 
	* @throws
	 */
	public static JsonConfig getDateJsonConfig(String format){
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor(format)); 
		return jsonConfig;
	}
	
	public static JsonConfig getDateJsonConfig(){
		return getDateJsonConfig("yyyyMMddHHmmss");
	}
	
	
	
	/**
	 * 将json转换成Bean
	 * @param json
	 * @param clz
	 * @return
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 * @throws Exception
	 */
	public static <T> T toObject(String json, Class<T> clz) throws JsonParseException, JsonMappingException, IOException {
		
		T obj = null;
		obj = (T) objectMapper.readValue(json, clz);
		return obj;
	}
	
	/**
	 * 将对象转化为josn
	 * @param o
	 * @return
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 */
	public static String  writeValueAsString(Object o) throws JsonGenerationException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(o);
	}
	
	
	
	
}
